library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_arith.all;
entity negative_edge_trigger is
	port ( ADC_DATA, REF_L, REF_H : in signed (7 downto 0);
			start,clk ,rst: in std_logic;
			negative_edge_trigger_pulse: out std_logic
			);
end negative_edge_trigger;
architecture rtl of negative_edge_trigger is
	type states is (idle,original,threshold_low,threshold_high,triggered);
	signal pr_state,nx_state: states;
begin
	process(clk,rst)
	begin
		if(rst='1') then 
			pr_state <= original;
		elsif (clk'event and clk = '1') then
            pr_state <= nx_state;
		end if;
	end process;
	process(REF_L,REF_H,ADC_DATA,pr_state,start)
	begin
			case pr_state is
                when idle =>
                    if(start = '1') then
                        nx_state <= original;
                    else    
                        nx_state <= pr_state;
                    end if;
				when original =>
					if(ADC_DATA > REF_H) then
						nx_state <= threshold_high;
					else 
						nx_state<= pr_state;
					end if;
				when threshold_high =>
					if(ADC_DATA < REF_H) then
						nx_state <= threshold_low;
					else 
						nx_state <= pr_state;
					end if;
				when threshold_low =>
					if(ADC_DATA < REF_L) then
						nx_state <= triggered;
					elsif (ADC_DATA > REF_H) then
						nx_state <= threshold_high;
					else 
						nx_state <= pr_state;
					end if;
				when triggered =>
					nx_state <= idle;	
			end case;
	end process;
	negative_edge_trigger_pulse <= '1' when pr_state =triggered else '0';
end rtl;
			